package com.lovo.psc.controller;


import com.lovo.commom.util.QiniuUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("qiniu")
public class QiniuController {


    @RequestMapping("upload")
    public String getImgUrl(MultipartFile file) {
        if (file != null) {
            //构造一个带指定 Region 对象的配置类，指定存储区域，和存储空间选择的区域一致
            Configuration cfg = new Configuration(Region.huadong());
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            //...生成上传凭证，然后准备上传
            String accessKey = QiniuUtil.accessKey;
            String secretKey = QiniuUtil.secretKey;
            String bucket = QiniuUtil.bucket;
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String key = "shop/" + System.currentTimeMillis() + ".jpg";
            try {
                byte[] bytes = file.getBytes();
                //认证
                Auth auth = Auth.create(accessKey, secretKey);
                //认证通过后得到token（令牌）
                String upToken = auth.uploadToken(bucket);
                try {
                    //上传文件,参数：字节数组，key，token令牌
                    //key: 建议我们自已生成一个不重复的名称
                    Response response = uploadManager.put(bytes, key, upToken);
                    //解析上传成功的结果
//                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//                    System.out.println(putRet.key);
//                    System.out.println(putRet.hash);

                    return QiniuUtil.domainOfBucket + "/" + key;
                } catch (QiniuException ex) {
                    Response r = ex.response;
                    System.err.println(r.toString());
                    try {
                        System.err.println(r.bodyString());
                    } catch (QiniuException ex2) {
                        //ignore
                    }
                }
            } catch (IOException ex) {
                //ignore
            }
        }
        return "no";
    }
}
